package com.bzyd.mp.utils;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bzyd.mp.mapper.UserMapper;
import com.bzyd.mp.mapper.UserRoleMapper;
import com.bzyd.mp.model.po.User;
import com.bzyd.mp.model.po.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户上下文工具类
 * 此处是伪代码仿写
 */
@Component
public class UserContextUtil {

    //登录的用户账户
    private static String userName;

    //用户所在部门编码
    private static String deptCode;

    //用户拥有的角色编码
    private static Set<String> roleCodes;

    public static String getCurrentUser() {
        return UserContextUtil.userName;
    }

    public static String getDeptCode() {
        return UserContextUtil.deptCode;
    }

    public static Set<String> getRoleCodes() {
        return UserContextUtil.roleCodes;
    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    public void setUser(String userName) {
        UserContextUtil.userName = userName;
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getName, userName));
        UserContextUtil.deptCode = user.getDeptId();
        List<UserRole> list = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserName, userName));
        Set<String> roles = CollUtil.isNotEmpty(list) ? list.stream().map(o -> o.getRoleCode()).collect(Collectors.toSet()) : new HashSet<>();
        UserContextUtil.roleCodes = roles;
    }
}
